package xin.yangshuai.mybatisgeneratorweb.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * JdbcConnect
 *
 * @author shuai
 * @date 2021/8/2
 */
public class JdbcConnect {

    public static void main(String[] args) throws Exception {
        List<String> list = selectTable("jdbc:mysql://localhost:3306/mbg?serverTimezone=Asia/Shanghai", "root", "root", "log");
        for (String s : list) {
            System.out.println(s);
        }
    }

    public static List<String> selectTable(String url, String user, String password, String tablePrefix) throws Exception {
        if (tablePrefix == null) {
            tablePrefix = "";
        }

        // 1.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 2.获得数据库链接
        Connection conn = DriverManager.getConnection(url, user, password);
        // 3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
        // 预编译
        String sql = "show tables like ?";
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, tablePrefix + "%");
        ResultSet rs = statement.executeQuery();

        List<String> list = new ArrayList<>();
        // 4.处理数据库的返回结果(使用ResultSet类)
        while (rs.next()) {
            list.add(rs.getString(1));
        }

        // 关闭资源
        rs.close();
        statement.close();
        conn.close();

        return list;

    }
}
